package org.wwx.protocol;

import org.apache.catalina.Engine;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

/**
 * @date 2025/6/5
 * @author王闻薪
 */
public class HttpService {
    public void start(String hostname, Integer port) {
        final Tomcat tomcat = new Tomcat();

        final Server server = tomcat.getServer();
        final Service service = server.findService("Tomcat");

        final Connector connector = new Connector();
        connector.setPort(port);

        final Engine engine = new StandardEngine();
        engine.setDefaultHost(hostname);

        final StandardHost host = new StandardHost();
        host.setName(hostname);

        String contextPath = "";
        final StandardContext context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new  Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);
        tomcat.addServlet(contextPath,"dispatcher",new DispatcherServlet());
        context.addServletMappingDecoded("/*","dispatcher");

        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
